const express = require('express')
const socketIo = require('socket.io')
const app = express()
const http = require('http')
const server = http.createServer(app)

// data
const userList = {}
const roomId = {}

const socket = socketIo(server,{
    cors: '*'
})


socket.on('connection',(socket)=>{
    console.log('会议系统连接成功');
    let {userId} = socket.handshake.query
    console.log(userId);
    userList[userId] = {userId,socket}
    userList[userId].socket.emit('connection',{
        message: `用户${userId}连接成功`
    })
    userList[userId].socket.on('join',joinHandler)
    userList[userId].socket.on('offer',offerHandler)
    userList[userId].socket.on('answer',answerHandler)
    userList[userId].socket.on('candidate',candidateHandler)
})


server.listen('9003',()=>{
    console.log('会议服务开启，端口9003');
})


// listenEvent

function joinHandler(data){
    console.log(data);
    userList[data.userId].socket.join(data.roomId)
    let rooms = socket.sockets.adapter.rooms
    console.log('rooms',rooms.get(data.roomId));
    userList[data.userId].socket.broadcast.emit('joined',{
        message: `用户${data.userId}加入${data.roomId}房间`
    })
}
function offerHandler(data){
    userList[data.userId].socket.broadcast.emit('offer',data)
}
function answerHandler(data){
    userList[data.userId].socket.broadcast.emit('answer',data)
}
function candidateHandler(data){
    userList[data.userId].socket.broadcast.emit('candidate',data)
}
